package cn.yd.rb.service.serviceimpl;


import cn.yd.rb.mapper.CommentMapper;
import cn.yd.rb.mapper.EnsureMapper;
import cn.yd.rb.mapper.NovelMapper;
import cn.yd.rb.po.*;
import cn.yd.rb.service.EnsureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class EnsureServiceImpl implements  EnsureService{
    @Autowired
    private EnsureMapper ensureMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private NovelMapper novelMapper;
    @Override
    public List<Ensure> findEnsure(Integer novel_id, Integer userId) {
        EnsureExample ensureExample = new EnsureExample();
        EnsureExample.Criteria  criteria = ensureExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andIsLikeEqualTo(1);
        criteria.andNovelIdEqualTo(novel_id);
        List<Ensure> ensureList= ensureMapper.selectByExample(ensureExample);
        return ensureList;
    }

    @Override
    public void insertEnsure(Ensure ensure) {
        EnsureExample ensureExample = new EnsureExample();
        EnsureExample.Criteria  criteria = ensureExample.createCriteria();
        criteria.andUserIdEqualTo(ensure.getUserId());
        criteria.andNovelIdEqualTo(ensure.getNovelId());
        criteria.andCommentIdEqualTo(ensure.getCommentId());
        List<Ensure> ensureList = ensureMapper.selectByExample(ensureExample);
        if(ensureList.size()==0){
            ensureMapper.insertSelective(ensure);
        }else{
            ensureMapper.updateByExampleSelective(ensure,ensureExample);
        }
        //重新计算点赞数
        EnsureExample ensureExample2 = new EnsureExample();
        EnsureExample.Criteria  criteria2 = ensureExample2.createCriteria();
        criteria2.andCommentIdEqualTo(ensure.getCommentId());
        criteria2.andIsLikeEqualTo(1);
        List<Ensure> ensureList2 = ensureMapper.selectByExample(ensureExample2);

        Comment comment = commentMapper.selectByPrimaryKey(ensure.getCommentId());
        comment.setZcount(ensureList2.size());
        commentMapper.updateByPrimaryKey(comment);
    }
}
